package com.sun.hunk.struts.action;

import com.sun.hunk.hibernate.dao.SalesDAO;
import com.sun.hunk.hibernate.domain.Sales;
import com.sun.hunk.struts.HunkDispatchAction;
import com.sun.hunk.struts.form.SalesForm;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author sunil
 */
public class SalesAction extends HunkDispatchAction {

    public ActionForward action(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SalesForm salesForm = (SalesForm) form;
        if ("Save".equalsIgnoreCase(salesForm.getButton())) {
            return save(mapping, form, request, response);
        } else {
            return search(mapping, form, request, response);
        }
    }

    public ActionForward search(ActionMapping mapping, ActionForm f, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SalesForm form = (SalesForm) f;
        SalesDAO dao = new SalesDAO();
        Map<String, Object> map = new HashMap<String, Object>();       
        List<Sales> list = dao.find(map);
        request.setAttribute("saless", list);
        return mapping.findForward("sales");
    }

    public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SalesForm salesForm = (SalesForm) form;
        request.setAttribute("salesForm", new SalesForm());
        search(mapping, new SalesForm(), request, response);
        return mapping.findForward("sales");
    }

    public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SalesForm salesForm = (SalesForm) form;
        search(mapping, new SalesForm(), request, response);
        return mapping.findForward("sales");
    }

    public boolean validate(SalesForm salesForm, HttpServletRequest request) {
        
        return true;
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            SalesForm salesForm = (SalesForm) form;
            setMessage(request, "Sales deleted !");
        } catch (Exception e) {
            setError(request, "oops ! something went wrong.");
        }
        return mapping.findForward("message");
    }

}
